//
//  SiftCellViewController.m
//  WisdomZhuHai
//
//  Created by Ryan on 15-1-16.
//  Copyright (c) 2015年 wyd. All rights reserved.
//

#import "GlobalCellViewController.h"
#import "SportsDetailViewController.h"
#import "StrategyDetailViewController.h"
#import "DVSwitch.h"

@interface GlobalCellViewController ()

@property (nonatomic,strong) UIView* headerView;
@property (nonatomic,strong) UIView* headerPopupView;

@property (nonatomic,assign) int currentIndex;
@property (nonatomic,assign) int chooseTime;
@property (nonatomic,assign) int chooseCell;
@property (nonatomic,strong) NSMutableArray* storesList;
@property (nonatomic, strong) NSMutableArray* strategyList;
@property (nonatomic,strong) NSMutableArray* newsList;

@property (nonatomic, assign) int category_current;
@property (nonatomic,assign) double latitude;
@property (nonatomic,assign) double longitude;

@property (nonatomic, strong) DVSwitch *topSelectMenu;

@property (nonatomic, assign) int isMenuInited;

@end

@implementation GlobalCellViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.currentIndex = -1;
    self.category_current = 0;
    self.isMenuInited = 0;
    self.chooseCell = -1;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.title = @"定制结果";
    //    [self setEnableRefresh:YES];
    [self setEnableLoadMore:YES];
    self.pullTableViewDelegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, self.headerView.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height - self.headerView.bounds.size.height);
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0, self.tableView.bounds.size.width, 35)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    [self getGlobalSearch:self.category_current];
    UILabel *nothing = [[UILabel alloc] initWithFrame:CGRectMake(55, 200, 200, 20)];
    nothing.textAlignment = UITextAlignmentCenter;
    nothing.textColor = [Common colorWithRGB:0xb2b2b2];
    nothing.text = @"加载中";
    nothing.tag = 40000;
    [self.tableView addSubview:nothing];
}

- (void)valueChanged:(id)sender{
    DVSwitch* segmentedControl = sender;
    NSLog(@"%s line:%d segment has changed to %d", __FUNCTION__, __LINE__, segmentedControl.
          selectedIndex);
    
    if(self.category_current != segmentedControl.selectedIndex){
        self.category_current = segmentedControl.selectedIndex;
        [self pullTableViewDidTriggerRefresh:self.tableView];
    }
    
}

- (void)initMenuWithArray{
    if(self.topSelectMenu == nil){
        NSArray *menu = [NSArray arrayWithObjects:@"资讯", @"商家", @"攻略", nil];
        self.topSelectMenu = [DVSwitch switchWithStringsArray:menu];
        self.topSelectMenu.frame = CGRectMake(0, 0, 320, 35);
        self.topSelectMenu.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.sliderColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.labelTextColorInsideSlider = [UIColor colorWithRed:20/255.0 green:180/255.0 blue:220/255.0 alpha:1];
        self.topSelectMenu.labelTextColorOutsideSlider = [UIColor blackColor];
        self.topSelectMenu.cornerRadius = 5;
        [self.topSelectMenu addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:self.topSelectMenu];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Protocol request
- (void)getGlobalSearch:(int)category_id
{
    [[ProtocolManager shareInstance] getGlobalSearch:_keyword target:self returnCount:10 beginNo:_currentIndex + 1 selector:@selector(getGlobalSearchCallback:)];
}

#pragma mark - Protocol call back

- (void)getGlobalSearchCallback:(NSDictionary*)dic
{
    NSLog(@"getListCallback %@", dic);
    UILabel *nothing = (UILabel*)[self.tableView viewWithTag:40000];
    nothing.text = @"暂无结果...";
    nothing.hidden = NO;
    if (dic == nil) {
        [self resetPullTableViewState];
        return;
    }
    if (self.currentIndex == -1) {
        self.storesList = [NSMutableArray array];
        self.strategyList = [NSMutableArray array];
        self.newsList = [NSMutableArray array];
    }
    NSArray* storesList = nil;
    if (self.category_current == 0) {
        storesList = [Common valueForKey:P_V2_NEWS dic:dic];
        if ([storesList isKindOfClass:[NSArray class]]) {
            [self.newsList addObjectsFromArray:storesList];
            self.currentIndex += storesList.count;
        }
    } else if (self.category_current == 1){
        storesList = [Common valueForKey:P_V2_STORES dic:dic];
    } else {
        storesList = [Common valueForKey:P_V2_STRATEGY dic:dic];
        if ([storesList isKindOfClass:[NSArray class]]) {
            [self.strategyList addObjectsFromArray:storesList];
            self.currentIndex += storesList.count;
        }
    }
    if ([storesList isKindOfClass:[NSArray class]]) {
        [self.storesList addObjectsFromArray:storesList];
        self.currentIndex += storesList.count;
    }
    if (storesList.count < STORE_LIST_RETURN_COUNT) {
        [self setEnableLoadMore:NO];
    }
    else {
        [self setEnableLoadMore:YES];
    }
    [self initMenuWithArray];
    
    [self resetPullTableViewState];
    [self.tableView reloadData];
}


#pragma mark - Cell
- (void)cellSetup:(UITableViewCell*)cell index:(NSInteger)index;
{
    if (self.storesList.count <= 0) {
        return;
    }
    UILabel *nothing = (UILabel*)[self.tableView viewWithTag:40000];
    nothing.hidden = YES;
    NSDictionary *cellDic = _storesList[index];
    NSString *imgUrl = [Common valueForKey:P_LOGO_PATH dic:cellDic];
    NSString *title = [Common valueForKey:P_NAME dic:cellDic];
    NSString *districtName = [Common valueForKey:P_V2_DISTRICT_NAME dic:cellDic];
    NSString *type_name = [Common valueForKey:P_LABEL dic:cellDic];
    NSString *good = [Common valueForKey:P_V2_GOOD dic:cellDic];
    NSString *comment_cnt = [Common valueForKey:P_V2_COMMENT_CNT dic:cellDic];
    NSString *base_price = [Common valueForKey:P_BASE_PRICE dic:cellDic];
    UIImageView *image = (UIImageView*)[cell viewWithTag:1001];
    [image setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    UILabel *titleLab = (UILabel*)[cell viewWithTag:1002];
    NSString *gps = [Common valueForKey:P_V2_GPS dic:cellDic];
    NSString *webSite =[NSString stringWithFormat:@"%@",[Common valueForKey:P_V2_HAS_MICRO_SITE dic:cellDic]];
    UIImageView *websiteView = (UIImageView*)[cell viewWithTag:1007];
    if ([webSite isEqualToString:@"0"]) {
        websiteView.hidden = YES;
    }
    double distance = 0;
    //[titleLab setNumberOfLines:2];
    titleLab.text = title;
    //[titleLab sizeToFit];
    //CGRect frame = titleLab.frame;
    //frame.size.width = 216;
    //titleLab.frame = frame;
    [self tagSetup:cellDic titleLabHeight:-1 cell:cell];
    UILabel *price = (UILabel*)[cell viewWithTag:1005];
    if ([base_price isEqualToString:@""] || [base_price isEqualToString:@"免费"] || base_price == nil){
        [price removeFromSuperview];
    } else {
        NSArray *priceArray = [base_price componentsSeparatedByString:@"元"];
        price.text = [NSString stringWithFormat:@"%@%@",priceArray[0],@"元起"];
    }
    if (![gps isEqualToString:@""]) {
        distance = [self getDistance:gps] / 1000.0;
    }
    UILabel *districtNameLab = (UILabel*)[cell viewWithTag:2002];
    districtNameLab.text = [NSString stringWithFormat:@"    %.1fkm%@", distance, districtName];
    if (_latitude <= 0 && _longitude <= 0) {
        districtNameLab.text = [NSString stringWithFormat:@"    %@", districtName];
    }
    UILabel* thirdLab = (UILabel*)[cell viewWithTag:2007];
    thirdLab.text = type_name;
    UILabel* goodLab = (UILabel*)[cell viewWithTag:2004];
    goodLab.text = good;
    UILabel* CommontLab = (UILabel*)[cell viewWithTag:2006];
    CommontLab.text = comment_cnt;
}

- (double)getDistance:(NSString*)gps {
    NSArray *gpsArray = [gps componentsSeparatedByString:@","];
    double targetLat = [gpsArray[1] doubleValue];
    double targetLon = [gpsArray[0] doubleValue];
    self.latitude = [ProtocolManager shareInstance].latitude;
    self.longitude = [ProtocolManager shareInstance].longitude;
    CLLocationCoordinate2D c1;
    c1 = CLLocationCoordinate2DMake(targetLat, targetLon);
    CLLocationCoordinate2D c2;
    c2 = CLLocationCoordinate2DMake(_latitude, _longitude);
    BMKMapPoint point1 = BMKMapPointForCoordinate(c1);
    BMKMapPoint point2 = BMKMapPointForCoordinate(c2);
    CLLocationDistance distance = BMKMetersBetweenMapPoints(point1,point2);
    return distance;
}

//标签描绘
- (void)tagSetup:(NSDictionary*)cellDic titleLabHeight:(CGFloat)height cell:(UITableViewCell*)cell
{
    NSArray *tagsList = [Common valueForKey:P_TAGS dic:cellDic];
    NSString *open_time = [Common valueForKey:P_OPEN_TIME dic:cellDic];
    UIView* tagListView = tagListView = [cell viewWithTag:1003];
    if(tagsList.count <= 0){
        UILabel *openTimeLab = (UILabel*)[cell viewWithTag:2008];
        openTimeLab.text = open_time;
    } else {
        CGFloat tagX = 0.0;
        int count = [tagsList count] > 3 ? 3 : [tagsList count];
        for (int i = 0; i < count; i++) {
            NSDictionary *tagDic = tagsList[i];
            NSString *cover_path = [Common valueForKey:P_COVER_PATH dic:tagDic];
            NSArray *rgbArray = [[Common valueForKey:P_V2_RGB dic:tagDic] componentsSeparatedByString:@"#"];
            if ([cover_path isEqualToString:@""]) {
                NSString *rgb = [NSString stringWithFormat:@"%@%@", @"0x",@"18aaf6"];
                if (rgbArray.count > 1) {
                    rgb = [NSString stringWithFormat:@"%@%@", @"0x",rgbArray[1]];
                }
                NSString *name = [Common valueForKey:P_NAME dic:tagDic];
                UIView *tagView = [[UIView alloc] initWithFrame:CGRectMake(tagX, 0, 45, 16)];
                tagView.layer.cornerRadius = 3.0;
                unsigned int color = strtoul([rgb UTF8String],0,0);//nsstring 转 rgb
                tagView.backgroundColor = [Common colorWithRGB:color];
                UILabel *tagNameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tagView.frame.size.width, tagView.frame.size.height)];
                tagNameLab.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:10.0];
                tagNameLab.textAlignment = UITextAlignmentCenter;
                tagNameLab.textColor = [UIColor whiteColor];
                tagNameLab.text = name;
                [tagNameLab sizeToFit];
                CGRect frame = tagNameLab.frame;
                frame.size.width = MAX(tagNameLab.frame.size.width + 5, 45);
                frame.size.height = 16;
                frame.origin = tagView.frame.origin;
                tagView.frame = frame;
                frame.origin = tagNameLab.frame.origin;
                tagNameLab.frame = frame;
                [tagView addSubview:tagNameLab];
                [tagListView addSubview:tagView];
                tagX += tagView.frame.size.width + 5;
            } else {
                UIImageView *tagsImg = [[UIImageView alloc]initWithFrame:CGRectMake(tagX, 0, 12, 12)];
                [tagsImg setImageWithURL:[Common getFullDownloadPathByRelativePath:cover_path]];
                [tagListView addSubview:tagsImg];
                tagX += 20;
            }
        }
    }
}

- (void)strategyCell:(UITableViewCell*)cell index:(NSInteger)index
{
    if (self.strategyList.count <= 0 ) {
        return;
    }
    UILabel *nothing = (UILabel*)[self.tableView viewWithTag:40000];
    nothing.hidden = YES;
    NSDictionary *cellDic = _strategyList[index];
    NSString *img = [Common valueForKey:P_PHOTO dic:cellDic];
    NSString *name = [Common valueForKey:P_NAME dic:cellDic];
    UIImageView *imgView = (UIImageView*)[cell viewWithTag:20001];
    [imgView setImageWithURL:[Common getFullDownloadPathByRelativePath:img] placeholderImage:[UIImage imageNamed:@"map/icon_placehold"]];
    UIView *nameView = [cell viewWithTag:20002];
    UILabel *nameLab = (UILabel*)[cell viewWithTag:20003];
    nameLab.text = name;
    [nameLab sizeToFit];
    CGRect frame = nameLab.frame;
    frame.size.width = frame.size.width + 10;
    frame.size.height = nameView.frame.size.height;
    frame.origin.y = nameView.frame.origin.y;
    nameView.frame = frame;
    frame.origin.y = nameLab.frame.origin.y;
    nameLab.frame = frame;
}

//资讯Cell
#pragma mark - cell
- (void)NewsCellSetup:(UITableViewCell*)cell index:(NSInteger)index;
{
    if (self.newsList.count <= 0) {
        return;
    }
    UILabel *nothing = (UILabel*)[self.tableView viewWithTag:40000];
    nothing.hidden = YES;
    NSDictionary *cellDic = _newsList[index];
    NSString *imgUrl = [Common valueForKey:P_NPHOTO dic:cellDic];
    NSString *title = [Common valueForKey:P_NRTITLE dic:cellDic];
    NSArray *tagsList = [Common valueForKey:P_TAGS dic:cellDic];
    NSString *source_name = [Common valueForKey:P_V2_SOURCE_NAME dic:cellDic];
    NSString *comment_cnt = [Common valueForKey:P_V2_COMMENT_CNT dic:cellDic];
    UIImageView *image = (UIImageView*)[cell viewWithTag:1001];
    UIImageView *okImage = (UIImageView*)[cell viewWithTag:1007];
    okImage.hidden = YES;
    [image setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
    UILabel *titleLab = (UILabel*)[cell viewWithTag:1002];
    [titleLab setNumberOfLines:2];
    titleLab.text = title;
    [titleLab sizeToFit];
    CGRect frame = titleLab.frame;
    frame.size.width = 216;
    titleLab.frame = frame;
    [self NewsTagSetup:tagsList titleLabHeight:frame.size.height cell:cell];
    UILabel *price = (UILabel*)[cell viewWithTag:1005];
    [price removeFromSuperview];
    UIImageView *districtNameImg = (UIImageView*)[cell viewWithTag:2001];
    [districtNameImg removeFromSuperview];
    UILabel *districtNameLab = (UILabel*)[cell viewWithTag:2002];
    districtNameLab.text = source_name;
    UIImageView* goodImg = (UIImageView*)[cell viewWithTag:2003];
    [goodImg removeFromSuperview];
    UILabel* CommontLab = (UILabel*)[cell viewWithTag:2006];
    CommontLab.text = comment_cnt;
}

//标签描绘
- (void)NewsTagSetup:(NSArray*)tagsList titleLabHeight:(CGFloat)height cell:(UITableViewCell*)cell
{
    if(tagsList.count <= 0)
    {
        return;
    }
    CGFloat tagX = 0.0;
    int count = [tagsList count] > 3 ? 3 : [tagsList count];
    for (int i = 0; i < count; i++) {
        UIView* tagListView = nil;
        if (height < 20.0) {
            tagListView = [cell viewWithTag:1003];
        } else {
            tagListView = [cell viewWithTag:1004];
        }
        NSDictionary *tagDic = tagsList[i];
        NSArray *rgbArray = [[Common valueForKey:P_V2_RGB dic:tagDic] componentsSeparatedByString:@"#"];
        NSString *rgb = [NSString stringWithFormat:@"%@%@", @"0x",@"18aaf6"];
        if (rgbArray.count > 1) {
            rgb = [NSString stringWithFormat:@"%@%@", @"0x",rgbArray[1]];
        }
        NSString *name = [Common valueForKey:P_NAME dic:tagDic];
        UIView *tagView = [[UIView alloc] initWithFrame:CGRectMake(tagX, 0, 45, 16)];
        tagView.layer.cornerRadius = 3.0;
        unsigned int color = strtoul([rgb UTF8String],0,0);//nsstring 转 rgb
        tagView.backgroundColor = [Common colorWithRGB:color];
        UILabel *tagNameLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tagView.frame.size.width, tagView.frame.size.height)];
        tagNameLab.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:10.0];
        tagNameLab.textAlignment = UITextAlignmentCenter;
        tagNameLab.textColor = [UIColor whiteColor];
        tagNameLab.text = name;
        [tagNameLab sizeToFit];
        CGRect frame = tagNameLab.frame;
        frame.size.width = MAX(tagNameLab.frame.size.width + 5, 45);
        frame.size.height = 16;
        frame.origin = tagView.frame.origin;
        tagView.frame = frame;
        frame.origin = tagNameLab.frame.origin;
        tagNameLab.frame = frame;
        [tagView addSubview:tagNameLab];
        [tagListView addSubview:tagView];
        tagX += tagView.frame.size.width + 5;
    }
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.storesList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.category_current != 2) {
        return 85;
    }
    else {
        return 110;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommonCell"];
    // Configure the cell...
    if (self.category_current == 0) {
        if(cell == nil)
        {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CommonCell"  owner:self options:nil][0];
        }
        [self NewsCellSetup:cell index:indexPath.row];
    } else if (self.category_current == 1) {
        if(cell == nil)
        {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CommonCell"  owner:self options:nil][0];
        }
        [self cellSetup:cell index:indexPath.row];
    } else {
        if(cell == nil)
        {
            cell = [[NSBundle mainBundle] loadNibNamed:@"CommonCell"  owner:self options:nil][1];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [self strategyCell:cell index:indexPath.row];
    }
    return cell;
}

- (void)viewDidAppear:(BOOL)animated {
    self.chooseCell = -1;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= self.storesList.count) {
        return;
    }
    if (indexPath.row == self.chooseCell) {
        self.chooseTime++;
    } else {
        self.chooseTime = -1;
        self.chooseCell = indexPath.row;
    }
    if (_chooseTime == -1) {
        NSDictionary* dic = self.storesList[indexPath.row];
        int storeId = [[Common valueForKey:P_ID dic:dic] intValue];
        if (self.category_current == 0) {
            //        NSString *url = [Common valueForKey:P_URL dic:dic];
            NSString *url = [NSString stringWithFormat:@"%@/%@/getContentPage?id=%d",[ProtocolManager shareInstance].api_base_url,V2APINEWS,storeId];
            WebIOS *web = [[WebIOS alloc]initWithFrame:[Common shareInstance].contentFrame url:[Common getUrlByString:url]];
            web.target_id = [[Common valueForKey:@"id" dic:dic] intValue];
            web.type = @"NEWS";
            [self.navigationController pushViewController:web animated:YES];
        } else if (self.category_current == 1) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            SportsDetailViewController *viewCtrl = [[SportsDetailViewController alloc]init];
            viewCtrl.target_id = storeId;
            [self.navigationController pushViewController:viewCtrl animated:YES];
        } else {
            [self getContent:storeId];
        }
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Protocol request
- (void)getContent:(int)strategyId
{
    [[ProtocolManager shareInstance] getContent:strategyId target:self selector:@selector(getContentCallback:)];
}

#pragma mark - Protocol call back
- (void)getContentCallback:(NSDictionary*)dic
{
    NSLog(@"getContentCallback %@", dic);
    if (dic == nil) {
        return;
    }
    NSString *respCode = [Common valueForKey:P_RESPCODE dic:dic];
    if (![respCode isEqualToString:CODE_HANDLE_SUCCESS]) {
        return;
    }
    StrategyDetailViewController *strategyDetailViewCtrl = [[StrategyDetailViewController alloc] initWithFrame:self.view.bounds];
    strategyDetailViewCtrl.detailInfo = dic;
    int strategyId = [[Common valueForKey:P_ID dic:dic] intValue];
    for (NSDictionary* dic in self.strategyList) {
        int Id = [[Common valueForKey:P_ID dic:dic] intValue];
        if (Id == strategyId) {
            strategyDetailViewCtrl.strategyInfo = dic;
            break;
        }
    }
    [self.navigationController pushViewController:strategyDetailViewCtrl animated:YES];
}

#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
    self.currentIndex = -1;
    [self setPullTableIsLoadMore:YES];
    [self getGlobalSearch:self.category_current];
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
    [self getGlobalSearch:self.category_current];
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}

@end
